package com.sky.wsp.rabbitmq.controller;

import com.sky.wsp.rabbitmq.po.EventTypeEnum;
import com.sky.wsp.rabbitmq.po.MessageTypeEnum;
import com.sky.wsp.rabbitmq.po.MqMessage;
import com.sky.wsp.rabbitmq.po.UserPo;
import com.sky.wsp.rabbitmq.producer.MqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户账号事件消息
 */
@RestController
@RequestMapping("/user")
public class UserMqController {

    @Autowired
    MqProducer mqProducer;

    @GetMapping("demo")
    public String demo() {
        return "demo";
    }

    @GetMapping(value = "/fanout")
    public String fanout(String name, EventTypeEnum event) {
        UserPo userPo = getUserPo(name);
        MqMessage<UserPo> msg = getMsg(userPo, event);
        System.out.println("==> user fanout name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendFanout(msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/direct")
    public String direct(String name, EventTypeEnum event) {
        UserPo userPo = getUserPo(name);
        MqMessage<UserPo> msg = getMsg(userPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> user direct routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.senddirectMail(routingKey, msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/topic")
    public String topic(String name, EventTypeEnum event) {
        UserPo userPo = getUserPo(name);
        MqMessage<UserPo> msg = getMsg(userPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> user topic routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendtopicMail(routingKey, msg);
        return "ok: " + name;
    }

    private UserPo getUserPo(String name) {
        UserPo userPo = new UserPo();
        userPo.setId("userId");
        userPo.setTenantId("tenantId");
        userPo.setThirdId("thirdUserId");
        userPo.setUsername(name);
        userPo.setMd5Password("md5Password");
        return userPo;
    }

    private MqMessage<UserPo> getMsg(UserPo userPo, EventTypeEnum event) {
        return new MqMessage<>()
                .setMessageType(MessageTypeEnum.USER)
                .setEventType(event)
                .setData(userPo);
    }

    private String getRoutingKey(EventTypeEnum event) {
        return MessageTypeEnum.USER.name() + "." + event.name();
    }
}
